package top.hg.tool.modules.car.person;

import cn.hutool.core.util.NumberUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hg.tool.common.exception.CarException;
import top.hg.tool.common.util.Assert;
import top.hg.tool.common.util.R;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: skh
 * @Date: 2019/7/30 10:37
 * @Description:
 */
@RestController
@RequestMapping("/car")
@Api(value = "摇号人管理")
@Slf4j
public class LotteryPersonController {

    @Autowired
    private LotteryPersonService lotteryPersonService;

    @ApiOperation("新增摇号人")
    @PostMapping("/saveLotteryPerson")
    public R saveLotteryPerson(@RequestBody LotteryPersonEntity lotteryPersonEntity) {
        checkPersonForm(lotteryPersonEntity);
        Integer id = lotteryPersonService.saveLotteryPerson(lotteryPersonEntity);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("id", id);
        return R.success(map);
    }

    @ApiOperation("修改摇号人")
    @PostMapping("/updateLotteryPerson")
    public R updateLotteryPerson(@RequestBody LotteryPersonEntity lotteryPersonEntity) {
        checkPersonForm(lotteryPersonEntity);

        lotteryPersonService.updateLotteryPerson(lotteryPersonEntity);
        return R.success();
    }

    @ApiOperation("删除摇号人")
    @GetMapping("/deleteLotteryPerson")
    public R deleteLotteryPerson(Integer id) {

        lotteryPersonService.deleteLotteryPerson(id);
        return R.success();
    }

    @ApiOperation("查询摇号人列表")
    @GetMapping("/getLotteryPersonList")
    public R getLotteryPersonList(String openId) {
        Assert.isEmpty(openId,"openId不能为空");
        List<LotteryPersonEntity> lotteryPersonEntityList = lotteryPersonService.getLotteryPersonList(openId);
        return R.success(lotteryPersonEntityList);
    }

    @ApiOperation("根据id查询摇号人详情")
    @GetMapping("/getPersonById")
    public R getPersonById(Integer id) {
        LotteryPersonEntity lotteryPersonEntity = lotteryPersonService.getPersonById(id);
        return R.success(lotteryPersonEntity);
    }

    private void checkPersonForm(LotteryPersonEntity lotteryPersonEntity) {
        Assert.validateEntity(lotteryPersonEntity);

        if (lotteryPersonEntity.getApplyNum().length() != 13) {
            throw new CarException("请输入合法的13位摇号编号");
        }

        if (!NumberUtil.isInteger(lotteryPersonEntity.getApplyNum())) {
            throw new CarException("摇号编号必须是数字");
        }
    }
}
